﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel;
using DotNETX.Authentication;

namespace EIA.WCFSecurity
{
    public class DispatchTokenInspector : IDispatchMessageInspector
    {
        public string TokenHeadName { get; set; }
        public string TokenHeadNamespace { get; set; }

        #region Validate

        private static object s_LockObj = new object();
        private static ITokenManager TokenManager { get; set; }

        private static  bool TokenValidate(string token)
        {
            lock (s_LockObj)
            {
                if (null == TokenManager)
                {
                    string connStr = DotNETX.Utility.Config.AppConfigUtils.TryGetSetting<string>(typeof(DispatchTokenInspector), "EIA.Authentication.ConnectionString");
                    System.Data.IDbConnection con = DotNETX.Authentication.Db.MySql.ConnectionUtils.CreateMySqlConnection(connStr);

                    TokenManager = DotNETX.Authentication.Db.MySqlTokenManager.Create(con, "t_login_session", "ses_token", "stf_id", "login_time", "last_vist_time", "is_active");
                }

                DotNETX.Authentication.UserSession session = TokenManager.GetSession(token);
                return null != session;
            }
        }

        #endregion

        #region IDispatchMessageInspector 成员

        protected string GetHeaderValue(string key, string ns)
        {
            int index = OperationContext.Current.IncomingMessageHeaders.FindHeader(key, ns);
            if (index >= 0)
            {
                return OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(index);
            }
            return null;
        }

        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            string user_token = GetHeaderValue(TokenHeadName, TokenHeadNamespace);
            
            if (user_token != null)
            {
                bool b = TokenValidate(user_token);
                if(b)
                {
                    return null;
                }
                // 通过验证
            }
            throw new FaultException("UserToken无效，访问身份不合法！");
        }

        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
        }

        #endregion
    }
}
